<?php

namespace app\supermanager\model;

use think\Model;
use Carbon\Carbon;
use app\common\traits\model\TraitModel;

/**
 * 会员模块旅行币模型
 */
class Intergrates extends Model
{

    protected $table = 'integral_detail';
    const INTEGRAL_TO_MONEY_RATE = 1;
    const CURRENCYS =  'USD,CNY';
    //protected static $loginuser = '';
    
    use TraitModel;
	
	/**
	 * 关联营地
	 */
	public function camps(){
		return $this->belongsTo('Camps','camp_id');
	}
	
    //增加积分

    public function addIntergrates($intergrate, $user_id, $option = [])
    {
        $option = array_merge(['type' => '收入', 'remark' => '收入'], $option);
        return $this->intergrateOperation(abs($intergrate), $user_id, $option, false);
    }

    //减少积分
    public function reduceIntergrates($intergrate, $user_id, $option = [], $abs = false)
    {
        $option = array_merge(['type' => '消费', 'remark' => '消费'], $option);
        return $this->intergrateOperation((0 - abs($intergrate)), $user_id, $option, $abs);
    }
    /**
     * 积分操作
     * @param  [type] $intergrate [description]
     * @param  [type] $user_id    [description]
     * @param  string $type       [description]
     * @param  [type] $remark     [description]
     * @return [type]             [description]
     */
    protected function intergrateOperation($intergrate, $user_id, $option = [], $abs)
    {
        $user = model('Users')->get($user_id);

        if (!$user) {
            throw new \Exception("user is null", 1);
            
        }
        
        if ((int)$intergrate < 0 && $abs === true) {
            if ($user->integral < abs($intergrate)) {
                throw new \Exception("Deficiency of integral", -89);
            }
        }
        $user->integral = $user->integral + $intergrate;
        $user->save();
        $user_id = $user->id;
        $user_mobile = $user->mobile;
        $camp_id = $user->camp_id;
        $branch_id = model('Camps')->where('id',$camp_id)->value('branch_id');
        $logs = ['user_id' => $user_id, 'user_mobile' =>$user_mobile, 'type' => $option['type'], 'intergrate' => abs($intergrate), 'remark' => $option['remark'], 'camp_id' => $camp_id, 'branch_id' => $branch_id];
        $this->createIntergrateLogs($logs);
    }

    //积分流水,写入日志
    private function createIntergrateLogs($intergrate_info)
    {
        return self::create($intergrate_info, true);
    }
    /**
     * 获取用户积分
     * @return [type] [description]
     */
    public function getUserIntegral($user_id)
    {
        return self::get('integral');
    }
	
	/**
	 * 获取积分信息列表
	 */
	public function getIntegralLists($querys = [],$order="created_at desc")
    {
        return $this->getInfoList($querys,$order);
    }
	
	/**
	 * 获取会员账号
	 * @param $id
	 */
	public function getUserAccout($id){
	    return model('Users')->where('id',$id)->value('mobile');
	}
}
